package cn.pconline.autoclub.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

/**
 * @author 作者 guoqiang
 * @version 2014-2-12
 */
public class StringUtil {

    /**
     * 支持标签
     *
     * @param html
     * @return
     */
    public static String filterBack(String html) {
        if (StringUtils.isBlank(html)) {
            return "";
        }
        if (html.contains("&lt;br/&gt;")) {
            html = html.replaceAll("&lt;br/&gt;", "<br/>");
        }
        return html;
    }

    /**
     * 换行标签转成共用
     *
     * @param content
     * @return
     */
    public static String backBr(String content) {
        if (StringUtils.isBlank(content)) {
            return "";
        }
        if (content.contains("<br/>")) {
            content = content.replaceAll("<br/>", "\n");
        }
        return content;
    }

    public static String md5(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(text.getBytes("utf-8"));
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < digest.length; i++) {
                String b = Integer.toHexString(0xFF & digest[i]);
                if (b.length() == 1) {
                    buf.append('0');
                }
                buf.append(b);
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
        } catch (UnsupportedEncodingException e) {
        }
        return text;
    }

    /**
     * 相比于 byteSubstring(String str, int cutLen, String suspensionSymbol,
     * boolean isFilterUBB) 增加了过滤flash、audio、img和table
     *
     * @param str
     * @param cutLen
     * @return
     */
    public static String byteSubstring4Reply(String str, int cutLen) {
        //先放大3倍，防止去掉ubb后为空
        String s = byteSubstring(str, 1000, "...");
        s = simpleStringFilter(s, "url");
        s = simpleStringFilter(s, "email");
        s = simpleStringFilter(s, "em");
        s = simpleStringFilter(s, "FLASH");
        s = simpleStringFilter(s, "RM");
        s = simpleStringFilter(s, "code");
        s = simpleStringFilter(s, "quote");
        s = simpleStringFilter(s, "color");
        s = simpleStringFilter(s, "fly");
        s = simpleStringFilter(s, "move");
        s = simpleStringFilter(s, "glow");
        s = simpleStringFilter(s, "shadow");
        s = simpleStringFilter(s, "b");
        s = simpleStringFilter(s, "i");
        s = simpleStringFilter(s, "u");
        s = simpleStringFilter(s, "center");
        s = simpleStringFilter(s, "size");
        s = simpleStringFilter(s, "face");
        s = simpleStringFilter(s, "align");
        s = simpleStringFilter(s, "font");
        s = simpleStringFilter(s, "WMA");
        s = simpleStringFilter(s, "WMV");
        s = simpleStringFilter(s, "table");
        s = simpleStringFilter(s, "FLASH");
        s = simpleStringFilter(s, "audio");
        s = simpleStringFilter(s, "img");
        return byteSubstring(s, cutLen, "...");
    }
    
    public static String filterUbbCode(String str) {
        str = simpleStringFilter(str, "url");
        str = simpleStringFilter(str, "email");
        str = simpleStringFilter(str, "em");
        str = simpleStringFilter(str, "FLASH");
        str = simpleStringFilter(str, "RM");
        str = simpleStringFilter(str, "code");
        str = simpleStringFilter(str, "quote");
        str = simpleStringFilter(str, "color");
        str = simpleStringFilter(str, "fly");
        str = simpleStringFilter(str, "move");
        str = simpleStringFilter(str, "glow");
        str = simpleStringFilter(str, "shadow");
        str = simpleStringFilter(str, "b");
        str = simpleStringFilter(str, "i");
        str = simpleStringFilter(str, "u");
        str = simpleStringFilter(str, "center");
        str = simpleStringFilter(str, "size");
        str = simpleStringFilter(str, "face");
        str = simpleStringFilter(str, "align");
        str = simpleStringFilter(str, "font");
        str = simpleStringFilter(str, "WMA");
        str = simpleStringFilter(str, "WMV");
        str = simpleStringFilter(str, "table");
        str = simpleStringFilter(str, "FLASH");
        str = simpleStringFilter(str, "audio");
        str = simpleStringFilter(str, "img");
        return str;
    }

    /**
     * 过滤掉某个UBB的tag
     *
     * @param string 需要处理的字符串
     * @param filter 需要过滤的UBB的tag
     * @return 经过处理的字符串
     */
    public static String simpleStringFilter(String string, String filter) {
        if (string == null || string.trim().equals("")) {
            return string;
        }

        String pStr1 = "\\[unknown\\]";
        String pStr2 = "\\[/unknown\\]";
        if (filter.equalsIgnoreCase("url")) {
            pStr1 = "\\[url[^\\[\\]]*\\]";
            pStr2 = "\\[/url\\]";
        } else if (filter.equalsIgnoreCase("email")) {
            pStr1 = "\\[email=[^\\[\\]]*\\]";
            pStr2 = "\\[/email\\]";
        } else if (filter.equalsIgnoreCase("color")) {
            pStr1 = "\\[\\s*color\\s*=\\s*(#?[a-z0-9].*?)\\]";
            pStr2 = "\\[\\s*/color\\s*\\]";
        } else if (filter.equalsIgnoreCase("glow")) {
            pStr1 = "\\[glow=[^\\[\\]]*\\]";
            pStr2 = "\\[/glow\\]";
        } else if (filter.equalsIgnoreCase("shadow")) {
            pStr1 = "\\[shadow=[^\\[\\]]*\\]";
            pStr2 = "\\[/shadow\\]";
        } else if (filter.equalsIgnoreCase("size")) {
            pStr1 = "\\[size=[^\\[\\]]*\\]";
            pStr2 = "\\[/size\\]";
        } else if (filter.equalsIgnoreCase("face")) {
            pStr1 = "\\[face=[^\\[\\]]*\\]";
            pStr2 = "\\[/face\\]";
        } else if (filter.equalsIgnoreCase("align")) {
            pStr1 = "\\[align=[^\\[\\]]*\\]";
            pStr2 = "\\[/align\\]";
        } else if (filter.equalsIgnoreCase("font")) {
            pStr1 = "\\[font=[^\\[\\]]*\\]";
            pStr2 = "\\[/font\\]";
        } else if (filter.equalsIgnoreCase("img")) {
            pStr1 = "\\[img[^\\[\\]]*\\][^\\[]*";
            pStr2 = "\\[/img\\]";
        } else if (filter.equalsIgnoreCase("b")) {
            pStr1 = "\\[b\\]";
            pStr2 = "\\[/b\\]";
        } else if (filter.equalsIgnoreCase("em")) {
            pStr1 = "\\[em([0-9]*)\\]";
        } else if (filter.equalsIgnoreCase("FLASH")) {
            pStr1 = "\\[flash\\]";
            pStr2 = "\\[/flash\\]";
        } else if (filter.equalsIgnoreCase("audio")) {
            pStr1 = "\\[audio\\]";
            pStr2 = "\\[/audio\\]";
        } else {
            pStr1 = pStr1.replaceAll("unknown", filter);
            pStr2 = pStr2.replaceAll("unknown", filter);
        }

        if (("img").equals(filter)) { //图片替换为“图”
            string = filterSingel(string, pStr1, "img", "[图]");
            string = filterSingel(string, pStr2);
        } else if ("em".equals(filter)) {//替换em中的code为配置里对应的中文
            string = filterSingel(string, pStr1, "em", "表情");
        } else if ("FLASH".equals(filter)) {
            string = filterSingel(string, pStr1, "FLASH", "[视频]");
            string = filterSingel(string, pStr2);
        } else if ("audio".equals(filter)) {
            string = filterSingel(string, pStr1, "audio", "[音乐]");
            string = filterSingel(string, pStr2);
        } else if ("table".equals(filter)) {
            string = filterSingel(string, pStr1, "table", "[表格]");
            string = filterSingel(string, pStr2);
        } else {
            string = filterSingel(string, pStr1);
            string = filterSingel(string, pStr2);
        }
        int left = string.lastIndexOf("[");
        int right = string.lastIndexOf("]");
        if (left >= 0) {
            if (left > right) {
                string = string.substring(0, left);
            }
        }
        return string;
    }

    public static String filterSingel(String str, String regex) {
        return filterSingel(str, regex, "", "");
    }
    //替换单个ubb字符为指定的字符串

    public static String filterSingel(String str, String regex, String type, String replement) {
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(str);
        //Map<String, String> emotMap = null;
        boolean emot = "em".equals(type);
        boolean img = "img".equals(type);
        boolean flash = "FLASH".equals(type);
        boolean audio = "audio".equals(type);
        if (emot) {
//            AppConfigService appConfigService = (AppConfigService) EnvUtils.getEnv().getBean("appconfigService");
//            emotMap = appConfigService.getValueMapByName("emot");
        }
        int strLength = str.length();
        int begin = 0;
        StringBuilder sb = new StringBuilder();
        int emotCode = 0;
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            if (end <= strLength) {
                sb.append(str.substring(begin, start));
                if (img || flash || audio) {
                    sb.append(replement);
                }
                if (emot) {
                    try {
                        emotCode = Integer.parseInt(str.substring(start + 3, end - 1));
                        //String emStr = str.substring(start, end);
                    } catch (NumberFormatException e) {
                    }
                    if (emotCode > 0) {
//                        if (emotMap.get(emotCode + "") == null) {
//                            sb.append(replement);
//                        } else {
                        sb.append(convertFace(emotCode));
//                        }
                    }
                }
            } else {
                if (start < strLength) {
                    sb.append(str.substring(begin, start));
                }
            }
            begin = end;
        }
        sb.append(str.substring(begin, strLength));
        return sb.toString();
    }

    /**
     * 表情转换
     *
     * @param emotCode
     * @return
     */
    public static String convertFace(int emotCode) {
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(1001, "[顶]");
        map.put(1002, "[微笑]");
        map.put(1003, "[晕]");
        map.put(1004, "[汗]");
        map.put(1005, "[抱抱]");
        map.put(1006, "[狂笑]");
        map.put(1007, "[害羞]");
        map.put(1008, "[大哭]");
        map.put(1009, "[吐]");
        map.put(1010, "[问]");
        map.put(1011, "[闭嘴]");
        map.put(1012, "[鄙视]");
        map.put(1013, "[胜利]");
        map.put(1014, "[无语]");
        map.put(1015, "[美女]");
        map.put(1016, "[鬼脸]");
        map.put(1017, "[白眼]");
        map.put(1018, "[吻]");
        map.put(1019, "[凶]");
        map.put(1020, "[路过]");
        map.put(1021, "[口水]");
        map.put(1022, "[电话]");
        map.put(1023, "[委屈]");
        map.put(1024, "[握手]");
        map.put(1025, "[已阅]");
        map.put(1026, "[再见]");
        map.put(1027, "[抓狂]");
        map.put(1028, "[鼓掌]");
        map.put(1029, "[无聊]");
        map.put(1030, "[害怕]");
        map.put(1031, "[嘘]");
        map.put(1032, "[下台]");
        map.put(1033, "[偷看]");
        map.put(1034, "[加油]");
        map.put(1035, "[可怜]");
        map.put(1036, "[受伤]");
        map.put(1037, "[吃惊]");
        map.put(1038, "[帅气]");
        map.put(1039, "[睡觉]");
        map.put(1040, "[发火]");
        map.put(1041, "[酷]");
        map.put(1042, "[思考]");
        map.put(1043, "[得意]");
        map.put(1044, "[聪明]");
        map.put(1045, "[贪钱]");
        map.put(1046, "[痛苦]");
        map.put(1047, "[敬礼]");
        map.put(1048, "[牛气冲天]");
        String def = "[表情]";
        for (int key : map.keySet()) {
            if (key == emotCode) {
                def = map.get(key);
            }
        }
        return def;
    }

    /**
     * 根据字节数截取字符串，请参考byteSubstring(String, int) 不同的是，如果截取得到的字符串长度小于原字符串，会加入省略符号
     * 不过如果省略符号是null或者空串，也直接返回截取后的字符串
     *
     * @param str 需要处理的字符串
     * @param cutLen 需要截取的长度（字节数）
     * @param suspensionSymbol 省略符号
     * @return 经过截取的字符串
     */
    public static String byteSubstring(String str, int cutLen, String suspensionSymbol) {
        if (StringUtils.isEmpty(str)) {
            return str;
        }
        if (cutLen <= 0) {
            return "";
        }
        int reInt = 0;
        if (!StringUtils.isEmpty(suspensionSymbol)) {
            char[] sArray = suspensionSymbol.toCharArray();
            int suspensionSymbolLength = 0;
            for (int i = 0; i < sArray.length; i++) {
                suspensionSymbolLength += String.valueOf(sArray[i]).getBytes().length;
            }
            reInt += suspensionSymbolLength;
        }
        String reStr = "";
        char[] chars = str.toCharArray();
        if (cutLen < reInt) {
            cutLen = reInt;
        }
        for (int i = 0; (i < chars.length && cutLen > reInt); i++) {
            reInt += String.valueOf(chars[i]).getBytes().length;
            reStr += chars[i];
        }
        reStr = reInt > cutLen ? reStr.substring(0, reStr.length() - 1) : reStr;
        return !StringUtils.isEmpty(suspensionSymbol) && str.length() > reStr.length() ? reStr + suspensionSymbol
                : reStr;
    }

    /**
     * 获取字符串的长度，如果有中文，则每个中文字符计为2位
     *
     * @param value 指定的字符串
     * @return 字符串的长度
     */
    public static int length(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
                valueLength += 2;
            } else {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    /**
     * 用逗号串连起来
     *
     * @param arr
     * @return
     */
    public static String toString(Object[] arr) {
        StringBuilder sb = new StringBuilder();
        if (arr != null) {
            for (Object obj : arr) {
                sb.append(obj.toString()).append(",");
            }
        }
        if (sb.length() > 0) {
            return sb.toString().substring(0, sb.length() - 1);
        }
        return "";
    }
    
    /**
     * 以某字符串结尾，返回截取此字符串之后的字符串
     * @param preString
     * @param filterString
     * @return
     */
    public static String filterString(String preString, String... filterString) {
    	if(StringUtils.isBlank(preString) || filterString.length <= 0) {
    		return preString;
    	}
    	
    	String newString = preString;
    	for(int i=0; i<filterString.length; i++) {
    		if(preString.endsWith(filterString[i])) {
    			newString = preString.substring(0, preString.length() - filterString[i].length());
    			break;
        	}
    	}
    	return newString;
    }
}
